version 18.5

drop after
gen after = 1 if MDYbid >= td(15mar2019) & MDYbid < td(01apr2021)
replace after = 0 if MDYbid <= td(12feb2019) & MDYbid >= td(01apr2015)

/**/
replace firm_treatment = . if g28_plus == 21 | g28_plus == 24 /* 29Oct22*/

gen either_before_after = (after < .)
egen regionfirmTG = tag(regionfirmID either_before_after) if either_before_after == 1
egen after_regionfirmTG = tag(after regionfirmID) if after < .

cap drop q
gen q = pt_tech /*if pt_tech >= 100 & pt_tech < 200*/
gen q_valid = q if q > 100
gen q_invalid = (q==100|(q==.)) if percent_reserve < 2

gen abovereserve = percent_reserve > 1 
gen aboveres_eff = percent_reserve > 1 if percent_reserve < 2

sort id win_bid_pct
by id: replace win_bid_pct = win_bid_pct[_n-1] if _n > 1 & win_bid_pct == .

bys id: egen nb_valid = total(percent_reserve <= 1)
gen lownumbids = (nb_valid <3)

cap drop auction_treatment
bys id: egen auction_treatment = max(firm_treatment)
bys id: egen auction_control = min(firm_treatment)

cap drop temp
bys after regionfirmID: egen temp = mean(q) if after == 0 & q > 100 & q < .
bys regionfirmID: egen mean_q_before_byfirm = max(temp)
drop temp
bys after regionfirmID: egen temp = mean(q) if after == 1 & q > 100 & q < .
bys regionfirmID: egen mean_q_after_byfirm = max(temp)
drop temp
bys after regionfirmID: egen temp= sd(q) if after == 0 & q > 100 & q < .
bys regionfirmID: egen sd_q_before_byfirm = max(temp)
drop temp
bys after regionfirmID: egen temp= sd(q) if after == 1 & q > 100 & q < .
bys regionfirmID: egen sd_q_after_byfirm = max(temp)

bys regionfirmID: egen mean_q_byfirm = max(mean_q_before_byfirm)
bys regionfirmID: egen sd_q_byfirm = max(sd_q_before_byfirm)
cap drop temp
bys after g28_plus: egen temp = median(q_valid) if after == 0 
bys g28_plus: egen median_q_before_byg28 = max(temp) 
cap drop temp
bys after g28_plus: egen temp = mean(q_valid) if after == 0
bys g28_plus: egen mean_q_before_byg28 = max(temp)

gen pctbid_hq = percent_reserve if mean_q_byfirm > median_q_before_byg28 & mean_q_byfirm  < .
gen pctbid_lq = percent_reserve if mean_q_byfirm < median_q_before_byg28

gen negative_ldeltap = (ldelta1p_s < 0)

gen pctbid = percent_reserve
gen winner01 = (winner == 1)

